package com.jiutong.orderpay.pay.wx;

import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;

import com.jiutong.orderpay.pay.Payment;


public class WeixinUtils {

	public static String getRandomNumber(int n) {
		if (n <= 0)
			return null;
		String str = "";
		for (int i = 0; i < n; i++) {
			str += (int) (Math.random() * 10);
		}
		return str;
	}

	/**
	 * 统一下单
	 * 
	 * @param name
	 *            商品名称
	 * @param total_fee
	 *            价格（单位：分）
	 * @param ip
	 *            ip
	 */
	public static Map<String, String> payUnifiedorder(String name,
			int total_fee, String ip, String out_trade_no) {
		UnifiedorderPayReqDate unifiedorderPayReqDate = new UnifiedorderPayReqDate(
				Payment.WX.APP_ID, Payment.WX.PARTNER_ID, "", name, "", "",
				out_trade_no, "", total_fee, ip, "", "", "",
				Payment.WX.NOTIFY_URL, "APP", "", "");
		String postDataXML = unifiedorderPayReqDate.toXml();
		postDataXML = "\n" + postDataXML;
		System.out.println(postDataXML);

		try {
			String res = HttpUtils.postXml(Payment.WX.PAY_UNFIFIEDORDER_API,
					postDataXML);
			System.out.println(res);
			Map<String, String> map = XMLParser.getMapFromXML(res);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Payment.WX.PAY_SIGN_KEY);
		String result = MD5.MD5Encode(sb.toString()).toUpperCase();
		return result;
	}

}
